import '../public/index'
import url from '../data/url'
import request from '../data/request'
import {tableConfig, header} from '../data/config'
import store from 'store'
import {getUrlParam} from '../data/util'

const base = url.base,
  getHouseOrder = request.getHouseOrder,
  downHouseOrder = request.downHouseOrder

let param = getUrlParam('type')

let table

let app = {
  data: {
    date: new Date(),
    startTime: null,
    endTime: null,
    orderStatus: null,
    houseValue: null,
    getObj: null,
    downArr: [],
    totalPrice: null,
    allPrice: null,
    orderFrom: null
  },
  init: () => {
    if (param) {
      app.data.getObj = store.get(param)
      app.setTypeBtn()
    }
    app.setTable()
  },
  setTypeBtn: () => {
    // console.log('data:', app.data.getObj);
    // app.data.getObj.orderStatus;

    [...document.querySelectorAll('#edit-type li button')].forEach(k => {
      if ($(k).attr('type-id') == app.data.getObj.orderStatus) {
        $('#edit-type li .btn').removeClass('btn-primary')
        $(k).addClass('btn-primary')
      }
    });

    [...document.querySelectorAll('#edit-order-origin li button')].forEach(k => {
      if ($(k).attr('type-id') == app.data.getObj.orderFrom) {
        $('#edit-order-origin li .btn').removeClass('btn-primary')
        $(k).addClass('btn-primary')
      }
    });
  },
  setTable: () => {
    table = $('#table').bootstrapTable($.extend({}, tableConfig, {
      url: base + getHouseOrder,
      queryParams: function (params) {
        console.log('data:', app.data.getObj, {
          currentPage: params.pageNumber,
          pageSize: params.pageSize
        })
        if (app.data.getObj) {
          return $.extend({}, app.data.getObj, {
            currentPage: params.pageNumber,
            pageSize: params.pageSize
          })
        } else {
          return {
            currentPage: params.pageNumber,
            pageSize: params.pageSize
          }
        }
      },
      ajax: function (params) {  //  自定义ajax
        $.ajax({
          url: params.url,
          type: 'POST',
          contentType: params.contentType,
          headers: {
            myToken: Cookies.get('myToken')
          },
          data: params.data
        }).done(function (res) {
          console.log(res)
          app.data.allPrice = res.settlementBa
          res.object.elements.forEach(k => {
            if (app.data.totalPrice === null) {
              app.data.totalPrice = k.tradeAmount
            } else {
              app.data.totalPrice += k.tradeAmount
            }
          })

          let totalAmount = $('.totalAmount'); //新增统计金额

          if (totalAmount.length == 0) {

            let html = `<div class="pull-left totalAmount"><span class="amountTitle"></span><span class="amount">${(res.settlementBa / 1000000).toFixed(2)}</span><span class="unit"> 万元</span></div>`;

            $('.fixed-table-pagination').before(html)

          } else {

            $('.totalAmount .amount').text(( res.settlementBa / 1000000).toFixed(2))
          }

          params.success({
            total: res.object.totalRows,
            rows: res.object instanceof Array ? res.object : res.object.elements
          })

        })
      },
      columns: [
        {
          field: 'checked',
          checkbox: true,
          class: 'edit-check'
        },
        {
          field: 'id',
          title: '订单号',
          valign: 'middle',
          class: 'edit-order-num'
        },
        {
          field: 'devName',
          title: '开发商名称',
          valign: 'middle'
        },
        {
          field: 'buildName',
          title: '楼盘名称',
          valign: 'middle'
        },
        {
          field: 'backup2',
          title: '楼栋',
          valign: 'middle'
        },
        {
          field: 'roomName',
          title: '房号',
          valign: 'middle'
        },
        {
          field: 'tradeAmount',
          title: '定金金额',
          valign: 'middle',
          formatter: (index, row) => {
            // console.log('price', row)
            return (row.tradeAmount / 100).toFixed(2)
          }
        },
        {
          field: 'realName',
          title: '姓名',
          valign: 'middle'
        },
        {
          field: 'phone',
          title: '手机号',
          valign: 'middle'
        },
        {
          field: 'tradeTime',
          title: '时间',
          valign: 'middle',
          formatter: (index, row) => {
            let time
            time = new Date(row.tradeTime)
            return time.toLocaleDateString()
          }
        },
        {
          field: 'orderFrom',
          title: '订单来源',
          valign: 'middle',
          formatter: (index, row) => {
            let status
            switch (row.orderFrom) {
              case 1:
                status = '一体机'
                break
              case 2:
                status = 'POS'
                break
              default:
                status = '-'
            }
            return status
          }
        },
        {
          field: 'payStatus',
          title: '状态',
          valign: 'middle',
          formatter: (index, row) => {
            let status
            // console.log('datas', row.payStatus, row)
            switch (row.payStatus) {
              case 0:
                status = '待付款'
                break
              case 1:
                status = '已付款'
                break
              case 2:
                status = '已失败'
                break
              case 4:
                status = '已成交'
                break
              case 3:
              case 5:
                status = '已取消'
                break
            }
            // console.log('status:', status)
            return status
          }
        },
        {
          field: 'status',
          valign: 'middle',
          align: 'center',
          width: '240px',
          title: '操作',
          formatter: (index, row) => {
            console.log('row:', row)
            switch (row.payStatus) {
              case 0:
                return `<button class="btn btn-default edit-id" go-id="${row.id}">订单详情</button>
                        <button class="btn btn-default edit-cancel" edit-id="${row.id}" room-id="${row.roomId}">取消</button>`
                break
              case 1:
                return `<button class="btn btn-default edit-id" go-id="${row.id}">订单详情</button>
                        <button class="btn btn-default edit-cancel" edit-id="${row.id}" room-id="${row.roomId}">取消</button>
                        <button class="btn btn-default edit-go" edit-id="${row.id}" room-id="${row.roomId}">成交</button>`
                break
              case 2:
              case 4:
              case 3:
              case 5:
                return `<button class="btn btn-default edit-id" go-id="${row.id}">订单详情</button>`
                break
            }
          }
        }
      ]
    }))

    table.on('load-success.bs.table', () => {
      $('.amount').html(app.data.allPrice / 100)
      $('.amountTitle').html('金额统计 : ')
    })

    app.setDateTimePicker()
    app.bind()
  },
  getDateStr: (res, type) => {
    let str = `<input size="16" type="text" value="${res.getFullYear()
      }-${res.getMonth() + 1 > 9 ? res.getMonth() + 1 : '0' + (res.getMonth() + 1)
      }-${res.getDate() > 9 ? res.getDate() : '0' + res.getDate()
      }	&nbsp;${res.getHours() > 9 ? res.getHours() : '0' + res.getHours()
      }:${res.getMinutes() > 9 ? res.getMinutes() : '0' + res.getMinutes()}"
      ${type}=""   
         readonly>`
    return str
  },
  setDateTimePicker: () => {
    $('#edit-start-time').append(app.getDateStr(app.data.date, 'edit-start-time'))
    $('#edit-start-time').datetimepicker({format: 'yyyy-mm-dd hh:ii'}).on('changeDate', e => {
      let date = Date.parse(e.date)
      $(e.target).find('input').attr('edit-start-time', date)
      let res = new Date(date)
      let showDate = `${res.getFullYear()
        }-${res.getMonth() + 1 > 9 ? res.getMonth() + 1 : '0' + (res.getMonth() + 1)
        }-${res.getDate() > 9 ? res.getDate() : '0' + res.getDate()
        }  ${res.getHours() > 9 ? res.getHours() : '0' + res.getHours()
        }:${res.getMinutes() > 9 ? res.getMinutes() : '0' + res.getMinutes()}`
      $(e.target).find('input').val(showDate)

    })
    $('#edit-end-time').append(app.getDateStr(app.data.date, 'edit-end-time'))
    $('#edit-end-time').datetimepicker({format: 'yyyy-mm-dd hh:ii'}).on('changeDate', e => {
      let date = Date.parse(e.date)
      $(e.target).find('input').attr('edit-end-time', date)
      let res = new Date(date)
      let showDate = `${res.getFullYear()
        }-${res.getMonth() + 1 > 9 ? res.getMonth() + 1 : '0' + (res.getMonth() + 1)
        }-${res.getDate() > 9 ? res.getDate() : '0' + res.getDate()
        }  ${res.getHours() > 9 ? res.getHours() : '0' + res.getHours()
        }:${res.getMinutes() > 9 ? res.getMinutes() : '0' + res.getMinutes()}`
      $(e.target).find('input').val(showDate)

    })
  },
  bind: () => {
    //查询状态切换
    $('#edit-order-origin li').on('click', e => {
      $('#edit-order-origin li .btn').removeClass('btn-primary')
      $(e.target).addClass('btn-primary')
      if ($(e.target).attr('type-id')) {
        app.data.orderFrom = $(e.target).attr('type-id')
      } else {
        app.data.orderFrom = null
      }
    })

    $('#edit-type li').on('click', e => {
      $('#edit-type li .btn').removeClass('btn-primary')
      $(e.target).addClass('btn-primary')
      if ($(e.target).attr('type-id')) {
        app.data.orderStatus = $(e.target).attr('type-id')
      } else {
        app.data.orderStatus = null
      }
    })

    //查询按钮
    $('#btn-search').on('click', () => {
      let data = {
        startTime: $('#edit-start-time input').attr('edit-start-time'),
        endTime: $('#edit-end-time input').attr('edit-end-time'),
        houseValue: $('#edit-build-name input')[0].value
      }
      if (app.data.orderStatus) {
        data.orderStatus = app.data.orderStatus
      }
      app.data.orderFrom ? data.orderFrom = app.data.orderFrom : null
      table.bootstrapTable('refresh', {
        query: $.extend({
          currentPage: 1,
        }, data)
      })
    })

    //导出按钮
    $('#edit-out').on('click', () => {
      let data = '';
      [...document.querySelectorAll('input[name="btSelectItem"]')].forEach(k => {
        if ($(k).prop("checked")) {
          let val = $(k).parent().parent().find('.edit-order-num').text()
          // console.log(val)
          if (data == '') {
            data = val
          } else {
            data += ',' + val
          }
        }
      })
      if (data) {
        $.ajax({
          type: "POST",
          url: base + downHouseOrder,
          dataType: "json",
          data: {
            ids: data
          },
          headers: {
            myToken: Cookies.get('myToken')
          },
        }).then(res => {
          let str = res.path
          window.location.href = base + str
        })
      }
    })
  }
}

app.init()

$(document).on('click', '#table .edit-id', e => {
  window.location.href = `./detail.html?id=${$(e.target).attr('go-id')}`
})

$(document).on('click', '#table .edit-cancel', e => {
  let data = {
    id: $(e.target).attr('edit-id'),
    payStatus: 5,
    roomId: $(e.target).attr('room-id')
  }
  $.ajax({
    type: "POST",
    url: base + 'admin/houseOrder/editPayStatus.json',
    dataType: "json",
    data: data,
    headers: {
      myToken: Cookies.get('myToken')
    },
  }).then(() => {
    table.bootstrapTable('refresh', {
      query: $.extend({
        currentPage: 1,
      }, $('#searchForm').serializeObject())
    })
  })
})

$(document).on('click', '#table .edit-go', e => {
  let data = {
    id: $(e.target).attr('edit-id'),
    payStatus: 4,
    roomId: $(e.target).attr('room-id')
  }
  $.ajax({
    type: "POST",
    url: base + 'admin/houseOrder/editPayStatus.json',
    dataType: "json",
    data: data,
    headers: {
      myToken: Cookies.get('myToken')
    }
  })
    .then(() => {
      table.bootstrapTable('refresh', {
        query: $.extend({
          currentPage: 1,
        }, $('#searchForm').serializeObject())
      })
    })
})




